<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="../css/reset.css">
    <style>
        .wrap {
            margin: 10px;
        }

        .list {
            margin-top: 10px;
            line-height: 40px;
            text-indent: 10px;
        }

        .list li {
            border: 1px dashed #333;
        }

        .list li+li {
            border-top: 0;
        }
    </style>
</head>

<body>
    <div class="wrap">
        <button>替换元素</button>
        <ul class="list">
            <li class="first">01</li>
            <li>02</li>
            <li class="mid">03</li>
            <li>04</li>
            <li>05</li>
            <li class="last">06</li>
        </ul>
    </div>
</body>
<script>


    // 点击 替换元素 按钮 => 创建一个li替换mid

    var btn = document.getElementsByTagName("button")[0];
    var ul = document.getElementsByClassName("list")[0];
    var mid = document.getElementsByClassName("mid")[0];



    // 替换节点 => 父元素统筹

    // parent.replaceChild(newNode,oldNode)  => 用一个节点(页面/页面中已存在) 替换 另一个节点





    btn.onclick = function () {
        if (mid) {
            var li = document.createElement("li");
            li.innerText = "我是新增的li";
            li.setAttribute("class", "new");
            li.style.backgroundColor = randColor();
            li.onclick = function () {
                li.style.backgroundColor = randColor();
            }


            ul.replaceChild(li, mid);
            // ul.replaceChild(ul.firstElementChild, mid);
            mid = null;
        }

    }


    function randColor() {
        // return `rgba(${Math.round(Math.random() * 255)},${Math.round(Math.random() * 255)},${Math.round(Math.random() * 255)},1)`;

        var colorStr = "0123456789abcdef";  // 16 

        var str = "#";
        for (var i = 0; i < 6; i++) {
            // var index = Math.round(Math.random() * (colorStr.length - 1));
            var index = Math.floor(Math.random() * colorStr.length);
            var char = colorStr.charAt(index);
            str += char;
        }
        console.log(str);
        return str;
    }








</script>

</html>